package com.fesine.ssh.dao.impl;

import com.fesine.ssh.dao.UserDao;
import com.fesine.ssh.model.User;
import com.fesine.ssh.util.GenerateUUID;
import com.fesine.ssh.util.ShopException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

import java.text.SimpleDateFormat;
import java.util.List;

/**
 * Created by Fesine on 2016/2/16.
 */
@Repository("userDao")
public class UserDaoImpl implements UserDao {
    @Autowired
    private SessionFactory sessionFactory;

    private Session getCurrentSession() {
        return this.sessionFactory.getCurrentSession();
    }
    public User load(String id) {
        return (User) this.getCurrentSession().load(User.class, id);
    }

    @Override
    public User get(String id) {
        return (User) this.getCurrentSession().get(User.class, id);
    }

    @Override
    public List<User> findAll() {
        String hql = String.format("from User order by userId");
        List<User> userList =
                this.getCurrentSession().createQuery(hql).setCacheable(true).list();
        return userList;
    }

    @Override
    public List<User> findByEntity(User user) {
        String hql = toHql(user);
        List<User> userList =
                this.getCurrentSession().createQuery(hql).setCacheable(true).list();
        return userList;
    }

    @Override
    public List<User> findByEntity(User user, int offset, int pageSize) {
        String hql = toHql(user);
        Query query = this.getCurrentSession().createQuery(hql).setCacheable(true);
        query.setFirstResult(offset);
        query.setMaxResults(pageSize);
        List<User> userList =
                query.list();
        return userList;
    }

    /**
     * 将实体转换成hql查询语句
     * @param user
     * @return
     */
    private String toHql(User user){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        StringBuffer hql = new StringBuffer("from User where 1=1 ");
        if (null != user.getUserId()) {
            hql.append("and userId like '%" + user.getUserId() + "%' ");
        }
        if (null != user.getUsername()) {
            hql.append("and username like '%" + user.getUsername() + "%' ");
        }
        if (null != user.getSex()) {
            hql.append("and sex like '%" + user.getSex() + "%' ");
        }
        if (null != user.getQq()) {
            hql.append("and qq like '%" + user.getQq() + "%' ");
        }
        if (null != user.getEmail()) {
            hql.append("and email like '%" + user.getEmail() + "%' ");
        }
        if (null != user.getPhone()) {
            hql.append("and phone like '%" + user.getPhone() + "%' ");
        }
        if (null != user.getAddress()) {
            hql.append("and address like '%" + user.getAddress() + "%' ");
        }
        if (null != user.getRegTime()) {

            hql.append("and regTime >= '" + sdf.format(user.getRegTime()) + "' ");
        }
        if (null != user.getUpdateTime()) {
            hql.append("and regTime <= '" + sdf.format(user.getUpdateTime()) + "' ");
        }
        hql.append(" order by userId desc");
        return hql.toString();
    }

    @Override
    public void persist(User entity) {
        this.getCurrentSession().persist(entity);
    }

    @Override
    public String save(User entity) {
        entity.setId(GenerateUUID.getUUId());
        return (String) this.getCurrentSession().save(entity);
    }

    @Override
    public void update(User entity) {
        this.getCurrentSession().update(entity);
    }

    @Override
    public void saveOrUpdate(User entity) {
        this.getCurrentSession().saveOrUpdate(entity);
    }

    @Override
    public void delete(String id) {
        User entity = this.load(id);
        this.getCurrentSession().delete(entity);
    }

    @Override
    public void flush() {
        this.getCurrentSession().flush();
    }

    @Override
    public User findByUserId(String userId) {
        String hql = String.format("from User where userId='%s' order by userId desc", userId);
        List<User> list = this.getCurrentSession()
                .createQuery(hql).setCacheable(true).list();
        if (CollectionUtils.isEmpty(list)) {
            return null;
        } else {
            return list.get(0);
        }
    }

    @Override
    public List<User> findAll(int offset, int pageSize) {
        String hql = String.format("from User order by userId desc");
        Query query =this.getCurrentSession().createQuery(hql).setCacheable(true);
        query.setFirstResult(offset);
        query.setMaxResults(pageSize);
        List<User> userList = query.list();
        return userList;
    }

    @Override
    public boolean login(String username, String password) {
        String hql = String.format("from User where username='%s' and password='%s'",username,password);
        List<User> userList = this.getCurrentSession().createQuery(hql).setCacheable(true).list();
        if (userList.size()>0) {
            return true;
        }
        return false;
    }

    @Override
    public boolean checkUsername(String username) {
        String hql = String.format("from User where username='%s'", username);
        List<User> userList = this.getCurrentSession().createQuery(hql).setCacheable(true).list();
        if (userList.size() > 0) {
            return true;
        }
        return false;
    }

    @Override
    public int deleteByUserId(String userId) throws ShopException {
        int id;
        String hql = String.format("delete User where userId='%s'", userId);
        id = this.getCurrentSession().createQuery(hql).executeUpdate();
        if (0 == id) {
            throw new ShopException("删除失败！用户id["+userId+"]");
        }
        return id;
    }

}
